package com.com.gmail.at.vssabinin.client;

import java.awt.event.MouseEvent;
import java.text.SimpleDateFormat;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;


import DTO.ScheduleDTO;
import DTO.StationDTO;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.GroupLayout;

public class StationSchedule extends javax.swing.JDialog {
	private static final long serialVersionUID = 1L;

    public StationSchedule(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        setResizable(false);
        initComponents();
    }

    public static StationSchedule stationScheduleInstance = new StationSchedule(Main.mainInstance, true);
    private DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel();
    private  DefaultListModel listArrivalModel = new DefaultListModel();
    private  DefaultListModel listDepartureModel = new DefaultListModel();
    
    private SimpleDateFormat dataFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
    
    private void update() {
    	comboBoxModel.removeAllElements();
    	Main.mainInstance.client.sendThroughProtocol("clientManageStatDat", "");
        Protocol.Message message = Main.mainInstance.client.readThroughProtocol();
        if (message.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<StationDTO> station = (List<StationDTO>)message.getObject();
            for (int i = 0; i < station.size(); i++) {
            	comboBoxModel.addElement(station.get(i).getStationName());
            }
        } else if (message.getType().equals("no")) {
        	comboBoxModel.addElement("No stations in database");
        }
        StationSchedule.stationScheduleInstance.stationsName.setModel(comboBoxModel);
    }
   
    private void initComponents() {

        goBack = new javax.swing.JButton();
        stationsName = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        arrivalList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        departureList = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        search = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        goBack.setText("go back to the main menu");
        goBack.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                goBackMouseReleased(evt);
            }
        });

        stationsName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "No stations in DB" }));
        
        jScrollPane1.setViewportView(arrivalList);

        jScrollPane2.setViewportView(departureList);

        jLabel1.setText("Departure schedule");

        jLabel2.setText("Arrival schedule");

        jLabel3.setText("Select a station to view the schedule:");

        search.setText("search");
        search.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                searchMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        layout.setHorizontalGroup(
        	layout.createParallelGroup(Alignment.TRAILING)
        		.addGroup(Alignment.LEADING, layout.createSequentialGroup()
        			.addGap(166)
        			.addComponent(jLabel1)
        			.addPreferredGap(ComponentPlacement.RELATED, 354, Short.MAX_VALUE)
        			.addComponent(jLabel2)
        			.addGap(188))
        		.addGroup(layout.createSequentialGroup()
        			.addGap(18)
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addComponent(goBack)
        				.addGroup(layout.createSequentialGroup()
        					.addGap(4)
        					.addGroup(layout.createParallelGroup(Alignment.LEADING)
        						.addGroup(layout.createSequentialGroup()
        							.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 420, GroupLayout.PREFERRED_SIZE)
        							.addPreferredGap(ComponentPlacement.RELATED)
        							.addComponent(jScrollPane2, GroupLayout.PREFERRED_SIZE, 420, GroupLayout.PREFERRED_SIZE))
        						.addGroup(layout.createSequentialGroup()
        							.addGap(91)
        							.addComponent(jLabel3)
        							.addGap(92)
        							.addComponent(stationsName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        							.addGap(109)
        							.addComponent(search, GroupLayout.PREFERRED_SIZE, 108, GroupLayout.PREFERRED_SIZE)))))
        			.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
        	layout.createParallelGroup(Alignment.TRAILING)
        		.addGroup(layout.createSequentialGroup()
        			.addContainerGap()
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(stationsName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jLabel3)
        				.addComponent(search))
        			.addPreferredGap(ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
        			.addGroup(layout.createParallelGroup(Alignment.BASELINE)
        				.addComponent(jLabel1)
        				.addComponent(jLabel2))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addGroup(layout.createParallelGroup(Alignment.LEADING)
        				.addComponent(jScrollPane1, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE)
        				.addComponent(jScrollPane2, Alignment.TRAILING, GroupLayout.PREFERRED_SIZE, 293, GroupLayout.PREFERRED_SIZE))
        			.addPreferredGap(ComponentPlacement.UNRELATED)
        			.addComponent(goBack)
        			.addContainerGap())
        );
        getContentPane().setLayout(layout);

        pack();
    }
    private void searchMouseReleased(java.awt.event.MouseEvent evt) {
    	this.listArrivalModel.clear();
    	this.listDepartureModel.clear();
    	StationDTO station = new StationDTO();
    	station.setStationName((String) this.stationsName.getSelectedItem());
    	Main.mainInstance.client.sendThroughProtocol("clientGetArrivalSchedule", station);
        Protocol.Message message1 = Main.mainInstance.client.readThroughProtocol();
        if (message1.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<ScheduleDTO> schedules = (List<ScheduleDTO>)message1.getObject();
            for (int i = 0; i < schedules.size(); i++) {
            	this.listArrivalModel.addElement("Train number: " + schedules.get(i).getTrainNumber() + " date of departure: " + 
            			dataFormat.format(schedules.get(i).getDateOfDeparture()) + " to: " + schedules.get(i).getStation2());
            }
        } else if (message1.getType().equals("no")) {
        	this.listArrivalModel.addElement("No available trains");	
        }
        Main.mainInstance.client.sendThroughProtocol("clientGetDepartureSchedule", station);
        Protocol.Message message2 = Main.mainInstance.client.readThroughProtocol();
        if (message2.getType().equals("ok")) {
        	@SuppressWarnings("unchecked")
        	List<ScheduleDTO> schedules = (List<ScheduleDTO>)message2.getObject();
            for (int i = 0; i < schedules.size(); i++) {
            	this.listDepartureModel.addElement("Train number: " + schedules.get(i).getTrainNumber() + " date of arrival: " + 
            			dataFormat.format(schedules.get(i).getDateOfArrival()) + " from: " + schedules.get(i).getStation1());
            }
        } else if (message2.getType().equals("no")) {
        	this.listDepartureModel.addElement("No available trains");	
        }
        this.arrivalList.setModel(listArrivalModel);
        this.departureList.setModel(listDepartureModel);
    }

    private void goBackMouseReleased(MouseEvent evt) {
    	Main.mainInstance.loginViewSet();
        this.dispose();
    }
    
    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        this.update();
    }
    
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(StationSchedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(StationSchedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(StationSchedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(StationSchedule.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                StationSchedule dialog = new StationSchedule(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    
    private javax.swing.JButton goBack;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JList arrivalList;
    private javax.swing.JList departureList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JButton search;
    private javax.swing.JComboBox stationsName;
}
